function loadData(i, index) {
    return new Promise((resolve => {
        console.log("开始发送第" + index + "条数据")
        setTimeout(() => {
            console.log("接受第" + index + "条数据")
            resolve(i)
        }, Math.random() * 1000 + 1000)
    }))
}

var data = [1, 2, 3, 4, 5, 6, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17]

const limit = 3;

let pendingPromiseCount = 0;
const result = [];
let current = 0

////////////////////////////////////////////////////
function fetchData() {
    if (data.length === current) {
        return;
    }

    if (pendingPromiseCount < limit) {
        const url = data[current];
        pendingPromiseCount++;
        loadData(url, current).then((res) => {
            result.push(res);
        }).catch(() => {
            result.push(res);
        }).finally(() => {
            pendingPromiseCount--;
            fetchData();
        })
        current++;
        fetchData();
    }
}

// fetchData()
// console.log(result)
////////////////////////////////////////////////////
///////////////////////////////////////////////////////
// 加加入逐次执行
async function getResult() {
    const result = []
    const current = []
    for (let i = 0; i < data.length; i++) {
        try {
            const _result = await loadData(data[i], i)
            result.push(_result)
        } catch (e) {

        }
    }
    console.log("lllllllll", result)
}

//////////////////////////////////////////////////////
// getResult()
//

////////////////////////////////////////////////////////////////

function maxLimit(fetchFunc, data, limit) {
    return new Promise(resolve => {
        let pendingPromiseCount = 0;
        let current = 0
        const result = [];

        function fetchData() {
            if (data.length === current) {
                return
            }

            if (pendingPromiseCount < limit) {
                const url = data[current];
                pendingPromiseCount++;
                fetchFunc(url, current).then((res) => {
                    result.push(res)
                }).catch((e) => {
                    result.push(e)
                }).finally(() => {
                    pendingPromiseCount--;
                    fetchData()
                    if (current === data.length && pendingPromiseCount === 0) {
                        resolve(result);
                    }
                })
                current++
                fetchData()
            }
        }

        fetchData()
    })
}

maxLimit(loadData, data, 2).then(res => {
    console.log("res", res)
})


// 应用场景，文件上传。
// 异步有关的类似节流操作，比如弹幕
// 限制请求发送
